package com.zh.eventdispatch.activity;

import android.content.Intent;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author wally
 * @date 2021/06/05
 * 事件分发器
 */
public class ActivityEventDispatcher {
    /**
     * 监听器列表
     */
    private final List<ActivityEventObserver> mEventObservers = new CopyOnWriteArrayList<>();

    /**
     * 添加监听器
     */
    public void addObserver(ActivityEventObserver observer) {
        if (observer == null) {
            return;
        }
        if (mEventObservers.contains(observer)) {
            return;
        }
        mEventObservers.add(observer);
    }

    /**
     * 移除监听器
     */
    public void removeObserver(ActivityEventObserver observer) {
        if (observer == null) {
            return;
        }
        mEventObservers.remove(observer);
    }

    /**
     * 获取注册的监听器列表
     */
    public List<ActivityEventObserver> getEventObservers() {
        return mEventObservers;
    }

    /**
     * 分发onActivityResult
     */
    public boolean dispatchOnActivityResult(int requestCode, int resultCode, Intent data) {
        //倒序遍历
        for (int i = mEventObservers.size() - 1; i >= 0; i--) {
            ActivityEventObserver observer = mEventObservers.get(i);
            if (observer.onSupportActivityResult(requestCode, resultCode, data)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 分发onBackPressed
     */
    public boolean dispatchOnBackPressed() {
        for (int i = mEventObservers.size() - 1; i >= 0; i--) {
            ActivityEventObserver observer = mEventObservers.get(i);
            if (observer.onSupportBackPressed()) {
                return true;
            }
        }
        return false;
    }
}